﻿using DataTurnClient.Enum;
using DataTurnClient.Interface;
using DataTurnClient.Model;
using DataTurnClient.ViewModel;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Splat;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTurnClient.Server
{
    public class Tool : ITool
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public T JsonToList<T>(string filePath)
        {
            try
            {
                string jsonStr = File.ReadAllText(filePath);
                //反序列化
                var list = JsonConvert.DeserializeObject<T>(jsonStr);
                return list;
            }
            catch (Exception ex)
            {
                AddLog("读取配置文件错误" + ex.Message);
                return default(T);
            }
        }

        /// <summary>
        /// 传输一个文本，显示到界面
        /// </summary>
        /// <param name="conect"></param>
        public void AddLog(string content)
        {
            var viewModel = Locator.Current.GetService<MainTurnViewModel>();
            viewModel.AddLogCommand.Execute(content).Subscribe();
        }
        public string MsgShow(Job job)
        {
            string status = job.JobStatus == 1 ? "开" : "关";
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"《任务名》：{job.JobCode}-{job.JobName}");
            sb.AppendLine($"《任务描述》");
            sb.AppendLine($"{job.JobDetail}");
            sb.AppendLine($"《任务状态》：{ status}");
            sb.AppendLine($"《请求模式》：{ job.JobMode}");
            sb.AppendLine($"《任务路由》：{ job.JobRoute}");
            sb.AppendLine($"《任务运行时间》");
            sb.AppendLine($"{job.JobRunTime}");
            sb.AppendLine($"{job.JobWeek}");
            return sb.ToString();
        }

        public string LogShow(Log log)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"《发生时间》：{log.HappenTime}");
            sb.AppendLine($"《发生描述》");
            sb.AppendLine($"{log.HappenDtal}");
            return sb.ToString();
        }
        /// <summary>
        /// xml读取
        /// </summary>
        public Result<string> XmlRead(string name)
        {
            Result<string> result = new Result<string>();
            result.Code = 500;
            result.Message = "未找到改key";
            result.Success = false;
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load("Version.xml");
                System.Xml.XmlElement root = doc.DocumentElement;
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合 
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    string id = ((System.Xml.XmlElement)node).GetAttribute("id");   //获取Name属性值 
                    string Value = ((System.Xml.XmlElement)node).GetElementsByTagName("Value")[0].InnerText;
                    if (id == name)
                    {
                        result.Code = 200;
                        result.Message = "请求成功";
                        result.Success = true;
                        result.Data = Value.ToString();
                        return result;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"{name}请求XmlRead时遇到错误：{ex.Message}";
                result.Success = false;
                return result;
            }
        }
        /// <summary>
        /// xml写入
        /// </summary>
        public Result<string> XmlWrith(string key, string keyName)
        {
            string fileName = "Version.xml";
            Result<string>  result = new Result<string>();
            result.Code = 500;
            result.Message = "未找到改key";
            result.Success = false;
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(fileName);    //加载Xml文件 
                System.Xml.XmlElement root = doc.DocumentElement;   //获取根节点 
                System.Xml.XmlNodeList personNodes = root.GetElementsByTagName("Person"); //获取Person子节点集合
                foreach (System.Xml.XmlNode node in personNodes)
                {
                    System.Xml.XmlElement ele = (System.Xml.XmlElement)node;
                    if (ele.GetAttribute("id") == key)
                    {
                        System.Xml.XmlElement nameEle = (System.Xml.XmlElement)ele.GetElementsByTagName("Value")[0];
                        nameEle.InnerText = keyName;
                        result.Code = 200;
                        result.Message = "请求成功";
                        result.Success = true;
                        return result;
                    }
                }
                doc.Save(fileName);
                return result;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = $"{key}请求XmlWrith时遇到错误：{ex.Message}";
                result.Success = false;
                return result;
            }
        }

        /// <summary>
        /// 发送接口请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public Result<T> PostRequest<T>(string url,T data, DType.RequestType type)
        {
            Post<T> p = new Post<T>
            {
                Post_url = url,
                Post_data = data,
                Post_mode = type,
            };
            return p.PostSend();
        }

        /// <summary>
        /// 核心方法，接口请求
        /// </summary>
        /// <param name="jobList"></param>
        /// <param name="setList"></param>
        /// <param name="sender"></param>
        /// <returns></returns>
        public Result<string> Execute(List<Job> jobList, List<RouteLine> setList, object sender)
        {
            var jobs = jobList.Where(x => x.JobCode == sender.ToString()).FirstOrDefault();
            var service = Locator.Current.GetService<ITool>();
            var viewModel = Locator.Current.GetService<MainTurnViewModel>();
            try
            {
                Post<String> p = new Post<String>();
                string route = jobs.JobRoute.Split(':')[1];
                if (route != "") { route = route + "/"; }
                int line = Convert.ToInt32(jobs.JobRoute.Split(':')[0]);
                RouteLine session = setList.Where(x => x.Id == line).FirstOrDefault();
                p.Post_url = $"http://{session.Ip}:{session.Port}/{session.Path}/{route}{sender.ToString()}";
                p.Post_mode = (DType.RequestType)System.Enum.Parse(typeof(DType.RequestType), jobs.JobMode);
                StringBuilder sb = new StringBuilder();
                sb.Append("{}");
                p.Post_data = sb.ToString();
                Result<string> result = p.PostSend();
                result.Data = sender.ToString() + "-" + JsonConvert.SerializeObject(result);
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + JsonConvert.SerializeObject(result));
                return result;
            }
            catch (Exception ex)
            {
                Result<string> result = new Result<string>();
                result.Code = 500;
                result.Message = $"请求{sender.ToString()}时遇到错误：{ex.Message}";
                result.Success = false;
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + ex.Message);
                return result;
            }
        }

        /// <summary>
        /// 核心方法，检查任务运行星期内
        /// </summary>
        /// <param name="jobWeek"></param>
        /// <returns></returns>
        public bool IsWeek(string jobWeek)
        {
            var server = Locator.Current.GetService<TimeService>();
            return server.IsWeek(jobWeek);
        }

        /// <summary>
        /// 核心方法，检查是否在任务运行秒时分内
        /// </summary>
        /// <param name="jobTimeList"></param>
        /// <param name="newTime"></param>
        /// <returns></returns>
        public bool IsTime(List<JobTime> jobTimeList, List<string> newTime)
        {
            var server = Locator.Current.GetService<TimeService>();
            return server.IsTime(jobTimeList,newTime);
        }

        /// <summary>
        /// txt写入
        /// </summary>
        /// <param name="txtName"></param>
        /// <param name="txt"></param>
        public void WriterText(string txtName, string txt)
        {
            var server = Locator.Current.GetService<LogService>();
            server.WriterText(txtName,txt);
        }
    }
}
